package com.gc.controller;

import com.gc.pojo.SysMenuOne;
import com.gc.pojo.SysUser;
import com.gc.services.MenuService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("sys")
public class SysController {

    @Autowired
    private MenuService menuService;

    @PostMapping("login")
    public String loginHTML(String loginName, String password, Model model){
        //获取当前的用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(loginName, password);
        try {
            subject.login(token);  //执行登录
            //登录成功后...
            SysUser currentUser = (SysUser) subject.getPrincipal();
            Session session = subject.getSession();
            currentUser.setPassword("");
            //设置用户session
            session.setAttribute("cur_user",currentUser);
            //设置菜单目录
            List<SysMenuOne> menus = menuService.getMyMenus(currentUser.getUserId());
            //todo 封装list<list<menu>>  在导航栏展示
            session.setAttribute("menus",menus);
            return "redirect:/index";
        } catch (UnknownAccountException e) {
            model.addAttribute("msg","用户未注册");
            return "login";
        } catch (IncorrectCredentialsException e) {
            model.addAttribute("msg","密码错误");
            return "login";
        }
    }

    @GetMapping("logout")
    public String logout(){
        //获取当前的用户
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "login";
    }
}
